package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            //and方法
            wrapper.and((queryWrapper) -> {
                queryWrapper.eq("brand_id", key).or().like("name", key);
            });
        }
        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    //联级修改  及修改品牌信息还修改（品牌-菜单分类关联表信息）
    @Override
    @Transactional
    public void updateBrandDetail(BrandEntity brand) {
        //修改品牌-菜单分类关联表中的brandName
        //保证冗余字段名一致
        if (!StringUtils.isEmpty(brand.getName())) {
            QueryWrapper<CategoryBrandRelationEntity> wrapper = new QueryWrapper();
            wrapper.eq("brand_id", brand.getBrandId());
            CategoryBrandRelationEntity entity = new CategoryBrandRelationEntity();
            entity.setBrandName(brand.getName());
            categoryBrandRelationService.update(entity, wrapper);

            //TODO 更新其他关联字段
        }
        baseMapper.updateById(brand);
    }

}